package com.dkd.manage.service.impl;

import java.util.Date;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.dkd.common.constant.DkdContants;
import com.dkd.common.utils.DateUtils;
import com.dkd.common.utils.SecurityUtils;
import com.dkd.common.utils.StringUtils;
import com.dkd.common.utils.spring.SpringUtils;
import com.dkd.manage.domain.Emp;
import com.dkd.manage.domain.TaskDetails;
import com.dkd.manage.domain.VendingMachine;
import com.dkd.manage.domain.dto.TaskDTO;
import com.dkd.manage.domain.vo.TaskVO;
import com.dkd.manage.mapper.EmpMapper;
import com.dkd.manage.mapper.TaskDetailsMapper;
import com.dkd.manage.service.ITaskDetailsService;
import com.dkd.manage.service.IVendingMachineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.dkd.manage.mapper.TaskMapper;
import com.dkd.manage.domain.Task;
import com.dkd.manage.service.ITaskService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 工单Service业务层处理
 *
 * @author ljt
 * @date 2025-02-20
 */
@Service
public class TaskServiceImpl implements ITaskService {
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private IVendingMachineService vendingMachineService;
    @Autowired
    private TaskDetailsMapper taskDetailsMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ITaskService taskService;

    /**
     * 查询工单
     *
     * @param taskId 工单主键
     * @return 工单
     */
    @Override
    public Task selectTaskByTaskId(Long taskId) {
        return taskMapper.selectTaskByTaskId(taskId);
    }

    /**
     * 查询工单列表
     *
     * @param task 工单
     * @return 工单
     */
    @Override
    public List<Task> selectTaskList(Task task) {
        return taskMapper.selectTaskList(task);
    }

    /**
     * 查询工单列表
     *
     * @param task 工单
     * @return 工单
     */
    @Override
    public List<TaskVO> selectTaskVOList(Task task) {
        return taskMapper.selectTaskVOList(task);
    }

    /**
     * 新增工单
     *
     * @param dto 工单
     * @return 结果
     */
    @Transactional
    public int insertTaskDTO(TaskDTO dto) {
//        0.dto 转换成 po
        Task task = new Task();
        BeanUtil.copyProperties(dto, task, "id", "createTime", "updateTime", "create_by", "update_by");
        task.setAssignorId(SecurityUtils.getUserId());
//        1.无论什么工单都要进行校验处理
        List<VendingMachine> machineList = vendingMachineService.selectVendingMachineList(VendingMachine.builder()
                .innerCode(dto.getInnerCode()).build());
        if (CollectionUtil.isEmpty(machineList)) {
            throw new RuntimeException("设备编号错误");
        }
        VendingMachine machine = machineList.get(0);
//        其次，要校验售后机状态与工单类型是否相符
//        a.投放工单，要为不运营的时候才正常，运营时抛出异常
        if (dto.getProductTypeId().equals(DkdContants.TASK_TYPE_DEPLOY)){
            if (!DkdContants.VM_STATUS_NODEPLOY.equals(machine.getVmStatus())) {
                throw new RuntimeException("设备状态错误");
            }
        }
//        b.补货工单，要为运营的时候才正常，不运营时抛出异常
//        c.维修工单，要为运营的时候才正常，不运营时抛出异常
//        d.撤机工单，要为运营的时候才正常，不运营时抛出异常
        if (dto.getProductTypeId().equals(DkdContants.TASK_TYPE_SUPPLY)){
            if (!DkdContants.VM_STATUS_RUNNING.equals(machine.getVmStatus())) {
                throw new RuntimeException("设备状态错误");
            }
        }
        if (dto.getProductTypeId().equals(DkdContants.TASK_TYPE_REPAIR)){
            if (!DkdContants.VM_STATUS_RUNNING.equals(machine.getVmStatus())) {
                throw new RuntimeException("设备状态错误");
            }
        }
        if (dto.getProductTypeId().equals(DkdContants.TASK_TYPE_REVOKE)){
            if (!DkdContants.VM_STATUS_RUNNING.equals(machine.getVmStatus())) {
                throw new RuntimeException("设备状态错误");
            }
        }


//        检查设备是否有未完成的同类型工单
//        List<Task> selectedTaskList = taskMapper.selectTaskList(Task.builder()
//                .innerCode(dto.getInnerCode())
//                .productTypeId(dto.getProductTypeId())
//                .taskStatus(DkdContants.TASK_STATUS_PROGRESS)
//                .build());
//        List<Task> selectedTaskList2 = taskMapper.selectTaskList(Task.builder()
//                .innerCode(dto.getInnerCode())
//                .productTypeId(dto.getProductTypeId())
//                .taskStatus(DkdContants.TASK_STATUS_CREATE)
//                .build());
        List<Task> undoneTaskList = taskMapper.selectUndoneTaskList(Task.builder()
                .innerCode(dto.getInnerCode())
                .productTypeId(dto.getProductTypeId())
                .build());
        if (CollectionUtil.isNotEmpty(undoneTaskList)) {
            throw new RuntimeException("已经有了同类型的工单，且该工单未完成");
        }

//        查询员工是否存在
        Emp emp = empMapper.selectEmpById(dto.getUserId());
        if (emp == null){
            throw new RuntimeException("员工不存在");
        }
//        校验员工区域是不是匹配的
        if (!emp.getRegionId().equals(machine.getRegionId())){
            throw new RuntimeException("员工区域不匹配");
        }
//        2.总之无论什么类型工单都要插入
        String username = SecurityUtils.getUsername();
        task.setCreateBy(username);
        task.setUpdateBy(username);
        Date nowDate = DateUtils.getNowDate();
        task.setCreateTime(nowDate);
        task.setUpdateTime(nowDate);
        task.setTaskCode(generateTaskCode());

        task.setTaskStatus(DkdContants.TASK_STATUS_CREATE);
        task.setUserName(emp.getUserName());
        task.setRegionId(machine.getRegionId());
        task.setAddr(machine.getAddr());


        int i = taskMapper.insertTask(task);

//        3.如果是补货工单，还要插入工单详情
        if (dto.getProductTypeId().equals(DkdContants.TASK_TYPE_SUPPLY)) {
            List<TaskDetails> taskDetailsList = dto.getDetails();
            for (TaskDetails details : taskDetailsList) {
                details.setTaskId(task.getTaskId());
                details.setCreateBy(username);
                details.setUpdateBy(username);
                details.setCreateTime(nowDate);
                details.setUpdateTime(nowDate);
            }
            taskDetailsMapper.batchInsertTaskDetails(taskDetailsList);
        }
        return i;
    }

    private String generateTaskCode() {
//        获取当前时间
        Date nowDate = DateUtils.getNowDate();
//        将当前时间格式化成字符串yyyymmdd
        String dateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, nowDate);
        String key ="com.dkd.code."+dateStr;
//       redis中没有这个key
        if (!redisTemplate.hasKey(key)){
//            给这个key设置值为1
            redisTemplate.opsForValue().set(key,1);
//            直接返回一个1,需要用0动态补齐4位，
            return dateStr+ "0001";
        }
        return dateStr+ StringUtils.leftPad(redisTemplate.opsForValue().increment(key).toString(),4,'0');
    }

    /**
     * 新增工单
     *
     * @param task 工单
     * @return 结果
     */
    @Override
    public int insertTaskDTO(Task task) {
        task.setCreateTime(DateUtils.getNowDate());
        return taskMapper.insertTask(task);
    }

    /**
     * 修改工单
     *
     * @param task 工单
     * @return 结果
     */
    @Override
    public int updateTask(Task task) {
        task.setUpdateTime(DateUtils.getNowDate());
        return taskMapper.updateTask(task);
    }

    /**
     * 批量删除工单
     *
     * @param taskIds 需要删除的工单主键
     * @return 结果
     */
    @Override
    public int deleteTaskByTaskIds(Long[] taskIds) {
        return taskMapper.deleteTaskByTaskIds(taskIds);
    }

    /**
     * 删除工单信息
     *
     * @param taskId 工单主键
     * @return 结果
     */
    @Override
    public int deleteTaskByTaskId(Long taskId) {
        return taskMapper.deleteTaskByTaskId(taskId);
    }

    /**
     * 取消工单
     * @param task
     * @return
     */
    @Override
    public int cancel(Task task) {
        //        有没有这样的工单
        Task selectTask = taskService.selectTaskByTaskId(task.getTaskId());
        if (selectTask == null) {
            throw new RuntimeException("工单不存在");
        }
//        校验工单
//        如果是已经取消的工单，抛出异常
//        如果是已经完成的工单，抛出异常
        if (DkdContants.TASK_STATUS_CANCEL.equals(task.getTaskStatus())) {
            throw new RuntimeException("工单状态错误");
        }
        if (DkdContants.TASK_STATUS_FINISH.equals(task.getTaskStatus())) {
            throw new RuntimeException("工单状态错误");
        }
//        设置po
        task.setTaskStatus(DkdContants.TASK_STATUS_CANCEL);
        task.setUpdateBy(SecurityUtils.getUsername());
        task.setUpdateTime(DateUtils.getNowDate());
        return taskService.updateTask(task);
    }
}
